/**
 * Created by ClearLiang on 2019/4/26
 * Function:
 * Desc:
 */
import React, {Component} from 'react';
import {
    ActivityIndicator,
    FlatList,
    RefreshControl, ScrollView,
    StyleSheet,
    Text,
    TouchableWithoutFeedback,
    View
} from 'react-native';
import JsonData from '../mainPages/Page1/Jsons';
import LinearGradient from 'react-native-linear-gradient';

const REQUEST_URL = "https://api.github.com/search/repositories?q=javascript&sort=stars&page=";
let pageNo = 1;//当前第几页
let totalPage = 2;//总的页数
let itemNo = 0;//item的个数

class TabScreen extends Component {

    // 初始化state
    constructor(props){
        super(props);
        this.state = {
            tabList: this.props.data,
            selectNo:1,
        };
    }

    _onSelect(itemData){
        this.setState({
            selectNo:itemData.id,
        });
        this.props.onTabClick(itemData.id);
        this.refs._tab.scrollToIndex({viewPosition: 0.5, index: itemData.id-1}); //viewPosition 0位于顶
    }

    // 返回单个
    renderRow(rowData){
        let item1,item2;
        if(this.state.selectNo === rowData.item.id){
            item1 = (
                <Text numberOfLines={1} ellipsizeMode={'tail'} style={{color: '#FF8F03', fontSize: 15}}>{rowData.item.name}</Text>);
            item2 = (
                <LinearGradient
                    start={{x: 0, y: 0}}
                    end={{x: 1, y: 0}}
                    colors={['#FF8F03', '#FF5301']}
                    style={{paddingHorizontal: 5, borderRadius: 10}}>
                    <Text
                        numberOfLines={1}
                        ellipsizeMode={'tail'}
                        style={{color: '#ffffff', fontSize: 12,}}>{rowData.item.tap}</Text>
                </LinearGradient>
            );
        }else {
            item1 = (
                <Text numberOfLines={1} ellipsizeMode={'tail'} style={{color: '#000000', fontSize: 15}}>{rowData.item.name}</Text>);
            item2 = (
                <LinearGradient
                    start={{x: 0, y: 0}}
                    end={{x: 1, y: 0}}
                    colors={['#f2f2f2', '#f2f2f2']}
                    style={{paddingHorizontal: 5, borderRadius: 10}}>
                    <Text
                        numberOfLines={1}
                        ellipsizeMode={'tail'}
                        style={{color: 'gray', fontSize: 12,}}>{rowData.item.tap}</Text>
                </LinearGradient>
            );
        }

        return (
            <View style={{width: (Config.deviceWidth - 5 - 10 * 5) / 5}}>
                <TouchableWithoutFeedback
                    style={{flex: 1, flexDirection: 'column'}}
                    onPress={this._onSelect.bind(this,rowData.item)}
                >
                    <View style={{flex: 1, flexDirection: 'column', justifyContent: 'center', alignItems: 'center'}}>

                        <View style={{marginBottom: 3}}>{item1}</View>
                        <View style={{}}>{item2}</View>

                    </View>
                </TouchableWithoutFeedback>
            </View>
        );
    }

    render() {

        return (
            <View style={[styles.root, styles.flex, {flexDirection: 'column'}]}>
                <View style={[styles.head,{height:50}]}>
                    <View style={[styles.flex, styles.row]}>
                        <FlatList
                            ref={'_tab'}
                            showsHorizontalScrollIndicator={false}
                            horizontal={true}
                            ItemSeparatorComponent={()=>{
                                return <View style={{width:1,backgroundColor: '#c8c8c8',marginHorizontal: 5,marginVertical:8}} />
                            }}
                            keyExtractor={(item, index) => index}
                            renderItem={this.renderRow.bind(this)}
                            data={this.state.tabList}
                        />
                    </View>
                </View>
            </View>
        );
    }
}


export default class FlatList_Tab extends Component {

    // 初始化state
    constructor(props) {
        super(props);
        this.state = {
            isLoading: true,
            //网络请求状态
            error: false,
            errorInfo: "",
            dataArray: [],
            showFoot:0, // 控制foot， 0：隐藏footer  1：已加载完成,没有更多数据   2 ：显示加载中
            isRefreshing:false,//下拉控制
        };
    }

    //网络请求——获取第pageNo页数据
    fetchData(pageNo) {
        //这个是js的访问网络的方法
        fetch(REQUEST_URL+pageNo)
            .then((response) => response.json())
            .then((responseData) => {
                let data = responseData.items;
                let dataBlob = [];
                let i = itemNo;

                data.map(function (item) {
                    dataBlob.push({
                        key: i,
                        value: item,
                    });
                    i++;
                });
                itemNo = i;
                ShowToast("itemNo:"+itemNo);
                let foot = 0;
                if(pageNo>=totalPage){
                    foot = 1;//listView底部显示没有更多数据了
                }

                this.setState({
                    //复制数据源
                    dataArray:this.state.dataArray.concat(dataBlob),
                    isLoading: false,
                    showFoot:foot,
                    isRefreshing:false,
                });
                data = null;
                dataBlob = null;
            })
            .catch((error) => {
                this.setState({
                    error: true,
                    errorInfo: error
                });
                console.log(error);
            })
            .done();
    }

    componentDidMount() {
        //请求数据
        this.fetchData( pageNo );
    }

    //加载等待页
    renderLoadingView() {
        return (
            <View style={styles.container}>
                <ActivityIndicator
                    animating={true}
                    color='red'
                    size="large"
                />
            </View>
        );
    }

    //加载失败view
    renderErrorView() {
        return (
            <View style={styles.container}>
                <Text>
                    Fail
                </Text>
            </View>
        );
    }

    //返回itemView
    _renderItemView({item}) {
        return (
            <View style={{backgroundColor: 'white'}}>
                <Text style={styles.title}>name: {item.value.name}</Text>
                <Text style={styles.content}>stars: {item.value.stargazers_count}</Text>
                <Text style={styles.content}>description: {item.value.description}</Text>
            </View>
        );
    }

    renderData() {

        return (

            <FlatList
                ListHeaderComponent={
                    <TabScreen
                        data={JsonData.tabList}
                        onTabClick={this._onTabClick.bind(this)}
                    />
                }
                onMomentumScrollEnd = {(event)=>{
                    let offsetY = event.nativeEvent.contentOffset.y; //滑动距离
                    let contentSizeHeight = event.nativeEvent.contentSize.height; //scrollView contentSize高度
                    let originScrollHeight = event.nativeEvent.layoutMeasurement.height; //scrollView高度
                    if (offsetY + originScrollHeight >= contentSizeHeight){
                        this._onEndReached();
                    }
                }}
                stickyHeaderIndices={[0]}
                style={this.props.style}
                data={this.state.dataArray}
                renderItem={this._renderItemView}
                ListFooterComponent={this._renderFooter.bind(this)}
                onEndReachedThreshold={1}
                ItemSeparatorComponent={this._separator}
            />
        );
    }

    _onTabClick(flag){
        //刷新数据
        ShowToast('刷新数据'+flag);
    }

    render() {
        //第一次加载等待的view
        if (this.state.isLoading && !this.state.error) {
            return this.renderLoadingView();
        } else if (this.state.error) {
            //请求失败view
            return this.renderErrorView();
        }
        //加载数据
        return this.renderData();
    }

    _separator(){
        return <View style={{height:1,backgroundColor:'#999999'}}/>;
    }

    _renderFooter(){
        if (this.state.showFoot === 1) {
            return (
                <View style={{height:30,alignItems:'center',justifyContent:'flex-start',}}>
                    <Text style={{color:'#999999',fontSize:14,marginTop:5,marginBottom:5,}}>
                        没有更多数据了
                    </Text>
                </View>
            );
        } else if(this.state.showFoot === 2) {
            return (
                <View style={styles.footer}>
                    <ActivityIndicator />
                    <Text>正在加载更多数据...</Text>
                </View>
            );
        } else if(this.state.showFoot === 0){
            return (
                <View style={styles.footer}>
                    <Text></Text>
                </View>
            );
        }
    }

    _onEndReached(){
        //ShowToast("新加载");
        //如果是正在加载中或没有更多数据了，则返回
        if(this.state.showFoot !== 0 ){
            return ;
        }
        //如果当前页大于或等于总页数，那就是到最后一页了，返回
        if((pageNo!==1) && (pageNo>=totalPage)){
            return;
        } else {
            pageNo++;
        }
        //底部显示正在加载更多数据
        this.setState({showFoot:2});
        //获取数据
        this.fetchData( pageNo );
    }
}

const styles = StyleSheet.create({
    root: {},
    head: {
        backgroundColor: '#f2f2f2',
    },
    body: {
        backgroundColor: 'white',
    },
    tab: {},
    flex: {
        flex: 1,
    },
    row: {
        flexDirection: 'row',
    },
    center: {
        alignItems: 'center',
        justifyContent: 'center',
    },

    container: {
        flex: 1,
        flexDirection: 'row',
        justifyContent: 'center',
        alignItems: 'center',
    },
    title: {
        fontSize: 15,
        color: 'blue',
    },
    footer:{
        flexDirection:'row',
        height:24,
        justifyContent:'center',
        alignItems:'center',
        marginBottom:10,
    },
    content: {
        fontSize: 15,
        color: 'black',
    }
});
